<template>
  <view class="upload-wrap">
    <up-upload
      :file-list="list"
      name="1"
      :accept="accept"
      :max-count="maxCount"
      :preview-full-image="previewFullImage"
      multiple
      @after-read="afterRead"
      @delete="deletePic"
    >
      <slot />
    </up-upload>
  </view>
</template>

<script lang="ts" setup>
import { uploadImage } from '@/api/common';
import type { UploadImageResult } from '@/api/common/types';

export interface FILE {
  size: number;
  type: string;
  url: string;
  status?: string;
  message?: string;
  [propName: string]: any;
}

const props = defineProps({
  list: {
    type: Array<FILE>,
    default: () => [],
  },

  accept: {
    type: String,
    default: 'media',
  },

  maxCount: {
    type: [String, Number],
    default: 52,
  },

  previewFullImage: {
    type: Boolean,
    default: true,
  },
});

const emits = defineEmits(['update:list']);

// 上传方法
const uploadFilePromise = (url: string): Promise<UploadImageResult> => {
  return uploadImage(url);
};
// 新增图片
const afterRead = async ({ file }: { file: Array<FILE> }) => {
  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  const lists: Array<FILE> = [...file];
  const fileList: Array<FILE> = props.list;
  let fileListLen = props.list.length;
  for (let i = 0; i < lists.length; i++) {
    const result: UploadImageResult = await uploadFilePromise(lists[i].url);
    const item: FILE = props.list[fileListLen];
    fileList.splice(fileListLen, 1, {
      ...item,
      status: 'success',
      message: '',
      url: result.url,
    });
    emits('update:list', fileList);
    fileListLen++;
  }
};

// 删除图片
const deletePic = ({ index }: { index: number }) => {
  const fileList = props.list;
  fileList.splice(index, 1);
  emits('update:list', fileList);
};
</script>
